<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form
        layout="vertical"
        ref="formRef"
        :model="formState"
        :rules="rules"
        @finish="handleSubmit"
      >
        <div class="option-column">
          <div class="column-title">耗材基础信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="耗材名称" name="name">
                <a-input
                  v-model:value="formState.name"
                  :disabled="isdisabled"
                  placeholder="请输入耗材名称"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="品牌" name="brand">
                <a-input
                  v-model:value="formState.brand"
                  :disabled="isdisabled"
                  placeholder="请输入品牌"
                />
              </a-form-item>
            </div>
            <div v-if="!(query?.type === 'add')" class="content-item">
              <a-form-item label="当前库存" name="name">
                <a-input
                  v-model:value="formState.total_stock"
                  :disabled="isdisabled"
                  placeholder="请输入当前库存"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="计量单位" name="unit">
                <a-input
                  v-model:value="formState.unit"
                  :disabled="isdisabled"
                  placeholder="请输入计量单位"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="安全库存下限" name="stock_min">
                <a-input
                  v-model:value="formState.stock_min"
                  :disabled="isdisabled"
                  placeholder="请输入安全库存下限"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="安全库存上限" name="stock_max">
                <a-input
                  v-model:value="formState.stock_max"
                  :disabled="isdisabled"
                  placeholder="请输入安全库存上限"
                />
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-column" v-if="query?.type === 'out'">
          <div class="column-title">出库信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="使用教师" name="user_id">
                <a-select
                  v-model:value="formState.user_id"
                  placeholder="请选择使用教师"
                >
                  <a-select-option
                    v-for="(item, index) in teacherOptions"
                    :key="index"
                    :value="item.value"
                    >{{ item.text }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="耗用库存" name="amount">
                <a-input-group compact>
                  <a-input
                    v-model:value="formState.amount"
                    placeholder="请输入耗用库存"
                    style="width: calc(100% - 31px)"
                  />
                  <a-button style="width: 30px; padding: 0" disabled>{{
                    formState.unit
                  }}</a-button>
                </a-input-group>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="使用时间" name="date">
                <a-date-picker
                  style="width: 100%"
                  v-model:value="date"
                  format="YYYY-MM-DD"
                  @change="onChangeAppointmentFormDate"
                />
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-column" v-if="query?.type === 'store'">
          <div class="column-title">入库信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="新增库存" name="amount">
                <a-input-group compact>
                  <a-input
                    v-model:value="formState.amount"
                    placeholder="请输入新增库存"
                    style="width: calc(100% - 31px)"
                  />
                  <a-button style="width: 30px; padding: 0" disabled>{{
                    formState.unit
                  }}</a-button>
                </a-input-group>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="使用时间" name="date">
                <a-date-picker
                  style="width: 100%"
                  v-model:value="formState.date"
                  format="YYYY-MM-DD"
                  @change="onChangeAppointmentFormDate"
                />
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-footer">
          <a-button class="opt-btn" @click="resetForm">取消</a-button>
          <a-button class="opt-btn" type="primary" @click="handleSubmit"
            >保存</a-button
          >
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import api from "@/api";
import SAPI from "@/api/system";
import router from "@/routers";
import { message } from "ant-design-vue";
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
//获取当前url参数
const query = computed(() => route.query);
const isdisabled = computed(() => query.value?.type !== "add"&& query.value?.type !== "edit");
const formState = ref({});
const customer_id = ref("");
//我的客户
const MyCustomers = async () => {
  const res = await SAPI.MyCustomers({});
  console.log(res);
  if (res) {
    customer_id.value = res[0].customer_id;
  }
};
const onChangeAppointmentFormDate = (dates, dateStrings) => {
  if (query.value?.type === "store") {
    formState.value.in_date = dateStrings || "";
  }
  if (query.value?.type === "out") {
    formState.value.out_date = dateStrings || "";
  }
  formState.value.date = dates;
};
//获取耗材详情
const getConsumableDetail = async () => {
  const res = await api.apiConsumableFetchModelPost({
    consumable_id: query.value.consumable_id,
  });
  console.log(res);
  formState.value = res.data;
};

//获取教师
const teacherOptions = ref([]);
const getApiTeacherOptionsPost = async () => {
  const res = await api.apiTeacherTeachersInMyCompaniesPost({});
  console.log(res);
  teacherOptions.value = res.data.map((item) => ({
    value: item?.user?.user_id,
    label: item?.user?.real_name,
    tag: "",
    text: item?.user?.real_name,
  }));
};
onMounted(async () => {
  await MyCustomers();
  if (query.value.consumable_id) {
    await getConsumableDetail();
  }
  if (query.value?.type === "out") {
    await getApiTeacherOptionsPost();
  }
});

const rules = ref({
  name: [{ required: true, message: "请输入耗材名称", trigger: "blur" }],
  brand: [{ required: true, message: "请输入品牌", trigger: "blur" }],
  unit: [{ required: true, message: "请输入计量单位", trigger: "blur" }],
  stock_min: [
    { required: true, message: "请输入安全库存下限", trigger: "blur" },
  ],
  stock_max: [
    { required: true, message: "请输入安全库存上限", trigger: "blur" },
  ],
  amount: [{ required: true, message: "请输入数量", trigger: "blur" }],
  date: [{ required: true, message: "请选择使用时间", trigger: "blur" }],
  user_id: [{ required: true, message: "请选择使用教师", trigger: "blur" }],
});
// formRef.value.resetFields();
//         //提示新增成功
//         message.success("新增成功");
// router.go(-1);
const resetForm = () => {
  formState.value = {};
  router.go(-1);
};
//创建耗材
const formRef = ref();
const createMaterial = async () => {
  formRef.value
    .validate()
    .then(async () => {
      const res = await api.apiConsumableCreatePost({
        name: formState.value.name,
        brand: formState.value.brand,
        unit: formState.value.unit,
        stock_min: formState.value.stock_min,
        stock_max: formState.value.stock_max,
        customer_id: customer_id.value,
      });
      if (res) {
        message.success("新增成功");
        resetForm();
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};

//更新耗材
const updateMaterial = async () => {
  formRef.value
    .validate()
    .then(async () => {
      const res = await api.apiConsumableUpdatePost({
        consumable_id: query.value.consumable_id,
        name: formState.value.name,
        brand: formState.value.brand,
        unit: formState.value.unit,
        stock_min: formState.value.stock_min,
        stock_max: formState.value.stock_max,
        customer_id: customer_id.value,
      });
      if (res) {
        message.success("更新成功");
        resetForm();
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};

// 入库
const storeConsumable = async () => {
  const res = await api.apiConsumableInCreatePost({
    consumable_id: query.value.consumable_id,
    amount: formState.value.amount,
    in_date: formState.value.in_date,
    enabled: true,
  });
  if (res) {
    message.success("入库成功");
    resetForm();
  }
};
// 出库
const outConsumable = async () => {
  const res = await api.apiConsumableOutCreatePost({
    consumable_id: query.value.consumable_id,
    user_id: formState.value.user_id,
    amount: formState.value.amount,
    out_date: formState.value.out_date,
    enabled: true,
  });
  if (res) {
    message.success("出库成功");
    resetForm();
  }
};

const handleSubmit = async () => {
  formRef.value
    .validate()
    .then(async () => {
      if (query.value?.type === "add") {
        await createMaterial();
      }
      if (query.value?.type === "edit") {
        await updateMaterial();
      }
      if (query.value?.type === "store") {
        await storeConsumable();
      }
      if (query.value?.type === "out") {
        await outConsumable();
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};
</script>
